const { app, BrowserWindow, dialog, ipcMain } = require('electron')
const path = require('path')

let win
app.whenReady().then(() => {
  win = new BrowserWindow({
    width: 600,
    height: 400,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      sandbox: false,
    },
  })
  win.loadFile(path.join(__dirname, '../renderer/index.html'))
  win.webContents.openDevTools({ mode: 'detach' })

  ipcMain.on('command', (event, type) => {
    if (type === 'open') showOpenDialog()
    else if (type === 'save') showSaveDialog()
    else if (type === 'message') showMessageBox()
  })
})

function showOpenDialog() {
  dialog
    .showOpenDialog({
      properties: ['openFile', 'multiSelections', 'openDirectory', 'showHiddenFiles'],
      filters: [
        { name: '图片', extensions: ['jpg', 'png', 'gif'] },
        { name: '视频', extensions: ['mkv', 'avi', 'mp4'] },
        { name: '自定义文件类型', extensions: ['json'] },
        { name: '任意类型', extensions: ['*'] },
      ],
    })
    .then((it) => console.log(it))
}

function showSaveDialog() {
  dialog
    .showSaveDialog({
      title: '请保存到一个隐蔽的位置',
    })
    .then((it) => console.log(it))
}

function showMessageBox() {
  dialog
    .showMessageBox(win, {
      icon: path.join(process.cwd(), 'apple.png'),
      type: 'info',
      title: '消息标题',
      message: '消息内容',
      detail: '更详细的信息',
      buttons: ['按钮1', '按钮2'],
      defaultId: 1,
    })
    .then((it) => {
      console.log('result', it)
    })
}
